package com.omt.tarjimdinek.util;

import static com.omt.tarjimdinek.conversation.ConversationHolder.getCurrentConversation;

import java.util.List;
import java.util.Locale;

import javax.faces.context.FacesContext;
import javax.inject.Named;

import org.springframework.context.annotation.Scope;
import org.springframework.context.i18n.LocaleContextHolder;

import com.omt.tarjimdinek.context.UserContext;
import com.omt.tarjimdinek.conversation.Conversation;

/**
 * Simple pass over to access static 'userContext'from EL.
 * Keeps also the user's preferred locale.
 *
 * @see org.springframework.security.web.authentication.AnonymousAuthenticationFilter
 */
@Named("userContext")
@Scope("session")
public class UserContextUtil {
    private static Locale locale;

    /**
     * It is invoked from the f:view tag. 
     * It defaults to the default JSF local.
     * 
     * @return the current user's locale.
     */
    public String getLocale() {
        if (locale == null) {
            locale = FacesContext.getCurrentInstance().getApplication().getDefaultLocale();
        }
        LocaleContextHolder.setLocale(locale);
        return locale.getLanguage();
    }
    
    public static Locale getLocaleInstance(){
    	if (locale == null) {
            locale = FacesContext.getCurrentInstance().getApplication().getDefaultLocale();
        }
        LocaleContextHolder.setLocale(locale);
        return locale;
    }

    public String switchToFrench() {
		return switchToLocale(Locale.FRENCH);
	}

   	public String switchToEnglish() {
        return switchToLocale(Locale.ENGLISH);
    }

    private String switchToLocale(Locale locale) {
    	this.locale = locale;
        FacesContext.getCurrentInstance().getViewRoot().setLocale(locale);
        LocaleContextHolder.setLocale(locale);
        
	    Conversation currentConversation = getCurrentConversation();
	
	    if (currentConversation != null) {
	        return FacesContext.getCurrentInstance().getViewRoot().getViewId() + "?faces-redirect=true&_cid_=" + currentConversation.getId();
	    } else {
	        return FacesContext.getCurrentInstance().getViewRoot().getViewId() + "?faces-redirect=true";
	    }
    }	

    public String getUsername() {
        return UserContext.getUsername();
    }

    public boolean isAnonymousUser() {
        return UserContext.ANONYMOUS_USER.equalsIgnoreCase(getUsername());
    }

    public boolean isLoggedIn() {
        return !isAnonymousUser();
    }

    public boolean isFrench() {
        if (locale != null) {
            return "fr".equals(locale.getLanguage());
        } else {
            // just in case, but should not happen
            return "fr".equals(LocaleContextHolder.getLocale().getLanguage());
        }
    }

    public List<String> getRoles() {
        return UserContext.getRoles();
    }

    public boolean hasRole(String role) {
        return UserContext.getRoles().contains(role);
    }
}